package net.beyondts.mplug;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * Project: mplug-project<br/>
 * Description: <br/>
 * Created at: 2019-01-30<br/>
 * Owned by beyondts.
 *
 * @author blazecrystal
 * @version 1.0.0
 */
@Component
public class SqlExecutor {
    private static final Logger LOGGER = LoggerFactory.getLogger(SqlExecutor.class);
    private JdbcTemplate template;

    @Autowired(required = false)
    public SqlExecutor(JdbcTemplate template) {
        this.template = template;
    }

    public void executeSqls(String[] sqls) {
        if (template != null && sqls != null && sqls.length > 0) {
            try {
                template.batchUpdate(sqls);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(sqls.length + " sqls executed while initializing");
                }
            } catch (Throwable t) {
                StringBuffer buf = new StringBuffer();
                for (int i = 0; i < sqls.length; i++) {
                    buf.append(i + 1);
                    buf.append(". ");
                    buf.append(sqls[i]);
                    if (i < sqls.length - 1) {
                        buf.append("\n\t");
                    }
                }
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("failed to execute sqls : \n\t" + new String(buf), t);
                }
            }
        }
    }
}
